import { GameConfig } from "../configs/GameConfig"
import { IRobotElement } from "../configs/Robot"
import { FightState } from "../etc/BoutState"
import { FightingRobotBehavior } from "../etc/FightingRobotBehavior"
import { StateMachine } from "../etc/StateMachine"

@Component
export default class RobotModel extends mw.Script {

    static robotMap:Map<number, RobotModel> = new Map()

    // 机器人guid
    @mw.Property({ multicast: true, replicated: true, onChanged:'onIDInit' })
    robotCfgID:number
    @mw.Property({ multicast: true, replicated: true})
    sceneID:number

    cfg:IRobotElement
    fsm:StateMachine<undefined, FightingRobotBehavior.EnumRobotState>

    private weaponGameObject:Model

    get character():Character{
        return <Character>this.gameObject
    }

    get position():Vector{
        return this.character.worldTransform.position
    }

    init(cfg:IRobotElement, fightState:FightState){
        this.cfg = cfg
        this.sceneID = -cfg.ID
        this.robotCfgID = cfg.ID

        this.fsm = FightingRobotBehavior.getBehavior(this, fightState)
        this.character.movementDirection = MovementDirection.AxisDirection
        RobotModel.robotMap.set(this.sceneID, this)
    }

    enable(){
        this.character.setVisibility(mw.PropertyStatus.On, true)
        this.character.setCollision(PropertyStatus.On, true)
    }
    
    disable(){
        this.character.worldTransform.position = new Vector(0,0,-3500)
        this.character.setVisibility(mw.PropertyStatus.Off, true)
        this.character.setCollision(PropertyStatus.Off, true)
    }

    translate(position:Vector){
        this.character.worldTransform.position = position
    }

    moveInput(direction:Vector){
        this.character.addMovement(direction)
    }

    private async onIDInit(){
        RobotModel.robotMap.set(-this.robotCfgID, this)
        this.cfg = GameConfig.Robot.getElement(this.robotCfgID)
        this.bindWeapon()
    }

    private async bindWeapon(){
        if(this.weaponGameObject) GameObjPool.despawn(this.weaponGameObject)

        await this.gameObject.asyncReady()

        this.weaponGameObject = GameObjPool.spawn('230F4F6E', GameObjPoolSourceType.Scene)
        this.weaponGameObject.setCollision(CollisionStatus.Off)
        this.character.attachToSlot(this.weaponGameObject, HumanoidSlotType.RightHand)
        this.weaponGameObject.localTransform.position = Vector.zero
        this.weaponGameObject.localTransform.rotation = Rotation.zero
    }

    static isRobot(sceneID:number){
        return sceneID <= 0 
    }
}